<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Demo</title>
</head>

<body>
    <h1>WebSocket Demo</h1>
    <div>
        <input type="text" id="clientId" placeholder="输入客户端ID">
        <button onclick="connect()">连接</button>
    </div>
    <div>
        <input type="text" id="message" placeholder="输入消息">
        <button onclick="sendMessage()">发送消息</button>
    </div>
    <ul id="response"></ul>

    <script>
        let ws = null;
        let currentClientId = null;
        const responseList = document.getElementById('response');

        function connect() {
            currentClientId = document.getElementById('clientId').value;
            if (!currentClientId) {
                alert('请输入客户端ID');
                return;
            }

            ws = new WebSocket('ws://localhost:3000');

            ws.onopen = () => {
                console.log('Connected to WebSocket server');
                // 发送注册信息
                ws.send(JSON.stringify({
                    type: 'register',
                    clientId: currentClientId
                }));
            };

            ws.onmessage = (event) => {
                const response = document.createElement('li');
                response.textContent = `服务端消息：${event.data}`;
                responseList.appendChild(response);
            };

            ws.onclose = () => {
                console.log('Disconnected from WebSocket server');
            };
        }

        const sendMessage = () => {
            const message = document.getElementById('message').value;
            const msg = document.createElement('li');
            msg.textContent = `客户端消息：${message}`;
            responseList.appendChild(msg);
            ws.send(message);
        };
    </script>
</body>

</html>